#include "stdafx.h"
#ifdef _DEBUG
	#undef THIS_FILE
	static char THIS_FILE[] = __FILE__;
	#undef DEBUG_NEW
	#define	DEBUG_NEW new(_NORMAL_BLOCK,__FILE__,__LINE__)
	#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////
auto_rwlock::auto_rwlock(void):__count__(0)
#ifdef	__strong__
	,__event__(CreateEvent(NULL,TRUE,TRUE,NULL))
#endif
{
	InitializeCriticalSection(&__cs__);
}

auto_rwlock::~auto_rwlock(void)
{
#ifdef	__strong__
	CloseHandle(__event__);
#endif
	DeleteCriticalSection(&__cs__);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
void auto_rwlock::LockForRead(void)
{
	EnterCriticalSection(&__cs__);
#ifdef	__strong__
	if(InterlockedIncrement(&__count__)==1)
		ResetEvent(__event__);
#else
	InterlockedIncrement(&__count__);
#endif
	LeaveCriticalSection(&__cs__);
}

void auto_rwlock::UnlockForRead(void)
{
#ifdef	__strong__
	if(InterlockedDecrement(&__count__)<1)
		SetEvent(__event__);
#else
	InterlockedDecrement(&__count__);
#endif
}

void auto_rwlock::LockForWrite(void)
{
	EnterCriticalSection(&__cs__);
#ifdef	__strong__
	WaitForSingleObject(__event__,INFINITE);
#else
	while(__count__>0)
		Sleep(10);
#endif
}

void auto_rwlock::UnlockForWrite(void)
{
	LeaveCriticalSection(&__cs__);
}
